"""
答手 - 快捷键版
用户按快捷键触发识别
"""
import ctypes
import win32con
import win32gui
import keyboard
from datetime import datetime
from colorama import Fore, init

from config.settings import Config
from common.tools.init_service import InitService
from common.tools.api_client import APIClient
from common.tools.ocr_service import OCRService
from common.tools.gpt_service import GPTService
from common.tools.screenshot_util import do_screenshot
from common.tools.remove_symbol import remove_symbol
from common.tools.clear_console import clear_console
from common.tools.out import out
from common.tools.get_config import get_config

# 打包命令（在项目根目录执行）：
# pyinstaller --onefile --icon=files/icon/DaShou.ico --paths=. apps/answer_shortcut.py

# 自动重置颜色
init(autoreset=True)

# 获取快捷键配置
config = get_config()
KEY_BOARD = config.get('快捷键', 'space')

# 获取程序的窗口句柄并置顶
hwnd = ctypes.windll.kernel32.GetConsoleWindow()
win32gui.SetWindowPos(hwnd, win32con.HWND_TOPMOST, 0, 0, 0, 0, win32con.SWP_NOMOVE | win32con.SWP_NOSIZE)


class ShortcutAnswerApp:
    """快捷键答题应用"""
    
    def __init__(self):
        self.api_client = APIClient()
        self.gpt_service = GPTService()
        self.login_data = None
        self.coordinates = None
        self.bd_url = None
        self.key_board = KEY_BOARD
    
    def initialize(self):
        """初始化应用"""
        init_service = InitService()
        init_service.check_and_create_files()
        self.login_data = init_service.login()
        self._parse_coordinates()
        
        # 如果是付费用户，预先获取百度 token
        if self.login_data['data']['roles'] == '付费' and self.login_data['data'].get('bdApiKey'):
            from common.gpt import GPT_BD
            self.bd_url = GPT_BD.get_token(
                self.login_data['data']['bdApiKey'],
                self.login_data['data']['bdSecretKey']
            )
    
    def _parse_coordinates(self):
        """解析坐标配置"""
        try:
            coordinate_key = 'coordinate' + str(self.login_data['data']['coordinate'])
            coordinate_str = self.login_data['data'][coordinate_key]
            # 新坐标格式：x1,y1,x2,y2（信息）; x3,y3,x4,y4（题目）; x5,y5,x6,y6（选项）
            x1, y1, x2, y2, x3, y3, x4, y4, x5, y5, x6, y6 = map(int, coordinate_str.split(','))
            # 目前逻辑仍然只使用题目和选项，不使用信息坐标
            self.coordinates = {
                'question': (x3, y3, x4, y4),
                'option': (x5, y5, x6, y6),
                'full': (x3, y3, x6, y6)
            }
        except Exception as e:
            print('│ 当前参数方案，数值异常，请检查配置文件：' + str(e))
            out()
    
    def run(self):
        """运行应用主循环"""
        while True:
            print('├───────────────────────────')
            print('│ ' + Fore.GREEN + f'按【{self.key_board}】键开始识别')
            
            # 等待快捷键
            keyboard.wait(self.key_board)
            
            clear_console()
            print('┌───────────────────────────────────────')
            
            # 识别题目
            self._recognize_question()
    
    def _recognize_question(self):
        """识别题目"""
        x1, y1, x2, y2 = self.coordinates['question']
        
        # 截图
        if not do_screenshot(x1, y1, x2, y2, 'question'):
            print('│ 截图失败，请重新识别')
            return False
        
        # OCR 识别
        question = OCRService.recognize(
            self.login_data['data']['txOcrSecretId'],
            self.login_data['data']['txOcrSecretKey'],
            self.login_data['data']['txAddress'],
            f'{Config.SCREENSHOT_DIR}/question.png',
            'question'
        )
        
        if question is None:
            print('│ ' + Fore.RED + '识别内容为空，请重新识别')
            return False
        
        print('│ 识别题目：' + question)
        
        # 查询题库
        if self.api_client.get_question_answer(remove_symbol(question)):
            return False
        
        print('├───────────────────────────')
        print('│ ' + Fore.YELLOW + '题库未查询到！')
        
        # 检查权限
        if not self._check_ai_permission():
            return False
        
        # 识别选项并查询 GPT
        return self._query_gpt(question)
    
    def _check_ai_permission(self):
        """检查 AI 功能权限"""
        if self.login_data['data']['roles'] == '白嫖':
            print('│ ———————————')
            print('│ ' + Fore.RED + '您尚未开通AI功能！')
            print('├───────────────────────────')
            return False
        
        if self.login_data['data']['weeks'] == 0:
            print('│ ———————————')
            print('│ ' + Fore.RED + '您已到期!AI功能已禁用！')
            print('├───────────────────────────')
            return False
        
        return True
    
    def _query_gpt(self, question):
        """识别选项并查询 GPT"""
        print('├───────────────────────────')
        
        x3, y3, x4, y4 = self.coordinates['option']
        
        # 截图选项
        if not do_screenshot(x3, y3, x4, y4, 'option'):
            print('│ 截图失败，请重新识别')
            return False
        
        # OCR 识别选项
        option = OCRService.recognize(
            self.login_data['data']['txOcrSecretId'],
            self.login_data['data']['txOcrSecretKey'],
            self.login_data['data']['txAddress'],
            f'{Config.SCREENSHOT_DIR}/option.png',
            'option'
        )
        
        # 组合问题
        full_question = '问题：' + question + ' ' + option
        print('│ ' + full_question)
        print('│ ———————————')
        
        # 并发查询所有 GPT 服务
        self.gpt_service.query_all(self.login_data, full_question)
        
        print('├───────────────────────────')
        print('│ ' + Fore.GREEN + 'GPT查询完成！')
        
        # 保存完整截图
        x1, y1, x4, y4 = self.coordinates['full']
        timestamp = datetime.now().strftime('%m-%d %H-%M-%S')
        do_screenshot(x1, y1, x4, y4, timestamp)
        
        return True


def main():
    """主函数"""
    app = ShortcutAnswerApp()
    app.initialize()
    app.run()


if __name__ == '__main__':
    main()
